package com.test.mooan.labama.activity_fragment_boom.process_boom;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.test.mooan.labama.R;
import com.test.mooan.labama.activity_fragment_boom.base_boom.BaseInfoActivity_boom;
import com.test.mooan.labama.bean_boom.config_info_boom.CountryInfo_boom;
import com.test.mooan.labama.bean_boom.process_boom.ProcessData_boom;
import com.test.mooan.labama.bean_boom.process_boom.ProcessInfo_boom;
import com.test.mooan.labama.bean_boom.process_boom.ProcessStep_boom;
import com.test.mooan.labama.constants_boom.Constant_boom;
import com.test.mooan.labama.utils_boom.Stringutil_boom;
import com.test.mooan.labama.utils_boom.helper_boom.UserInfoHelper_boom;
import com.test.mooan.labama.utils_boom.http_boom.HttpManager_boom;
import com.test.mooan.labama.view_boom.base_boom.BaseInfoInputViewManager_boom;
import com.test.mooan.labama.view_boom.info_input_boom.ContactRelationshipSelectViewManager_boom;
import com.test.mooan.labama.view_boom.info_input_boom.DatePickViewManager_boom;
import com.test.mooan.labama.view_boom.info_input_boom.GenderSelectViewManager_boom;
import com.test.mooan.labama.view_boom.info_input_boom.InputViewManager_boom;
import com.test.mooan.labama.view_boom.info_input_boom.SelectViewManager_boom;
import com.test.mooan.labama.view_boom.widget_boom.TitleView_boom;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.TreeMap;


public class InfoUpldActivity_boom extends BaseInfoActivity_boom {

    private LinearLayout groupLayout;

    private final ArrayList<BaseInfoInputViewManager_boom> infoInputViewManagers = new ArrayList<>();

    private ProcessStep_boom step;

    //尼日银行选择
    private String paramNameBankCode = "";
    private ProcessData_boom bankNameData;
    private final TreeMap<String,String> map_bankName_bankCode = new TreeMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_info_upload_boom);
        init();
    }

    @SuppressLint("InflateParams")
    private void init(){
        TitleView_boom titleView = findViewById(R.id.activity_info_upload_view_title);
        setBackBtn_boom(titleView.getBackIb());

        groupLayout = findViewById(R.id.activity_info_upload_layout_group);

        View topTipsView = findViewById(R.id.activity_info_upload_view_top_tips);
        TextView topTipsTv = findViewById(R.id.activity_info_upload_tv_top_tips);

        findViewById(R.id.activity_info_upload_btn_next).setOnClickListener(v -> {

            UserInfoHelper_boom.gInstance().addEventPoint((pageTag + "_SAVE_CLICK").toUpperCase());

            HttpManager_boom.getInstance().saveUserPointForBatch();

            for (BaseInfoInputViewManager_boom widgetsManager: infoInputViewManagers){
                if (!widgetsManager.checkInput()){
                    showToast_boom(getString(R.string.input_tip));
                    return;
                }
            }
            if (step ==null) return;
            String url = step.gApiUrl();
            if (url.isEmpty()) return;
            TreeMap<String,String> dataMap = new TreeMap<>();

            ArrayList<String> relashipList = new ArrayList<>();
            ArrayList<String> nameList = new ArrayList<>();
            ArrayList<String> phoneList = new ArrayList<>();

            for (BaseInfoInputViewManager_boom baseInfoInputViewManager: infoInputViewManagers){

                ProcessData_boom data = baseInfoInputViewManager.getData();
                if (data==null) continue;
                switch (data.gAction()) {
                    case Constant_boom.Data_Action_Relation ->
                            relashipList.add(((ContactRelationshipSelectViewManager_boom) baseInfoInputViewManager).getTextInput());
                    case Constant_boom.Data_Action_Name ->
                            nameList.add(baseInfoInputViewManager.getInput());
                    case Constant_boom.Data_Action_Phone ->
                            phoneList.add(baseInfoInputViewManager.getInput());
                    default -> dataMap.put(data.gParamName(), baseInfoInputViewManager.getInput());
                }

            }

            //添加联系人信息
            if (!TextUtils.isEmpty(step.gContactParamName())){
                JSONArray jsonArray = new JSONArray();
                for (int i=0;i<relashipList.size();i++){
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("relation",relashipList.get(i));
                        if (i<nameList.size()) jsonObject.put("fullName",nameList.get(i));
                        if (i<phoneList.size()) jsonObject.put("mobile",phoneList.get(i));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    jsonArray.put(jsonObject);
                }
                dataMap.put(step.gContactParamName(),jsonArray.toString());
            }

            HttpManager_boom.getInstance().uploadInfo(url,dataMap);
        });

        step = ProcessInfo_boom.getInstance().gStep(0);
        String stepName = ProcessInfo_boom.getInstance().gStepName(0);

        if (step == null) return;

        String topTips = step.gTopTips();

        if (!TextUtils.isEmpty(topTips)){
            topTipsView.setVisibility(View.VISIBLE);
            topTipsTv.setText(topTips);
        }else if ("personal_info".equalsIgnoreCase(stepName)){
            topTipsView.setVisibility(View.VISIBLE);
            topTipsTv.setText(getText(R.string.top_tips_personal));
        }else if ("contact_info".equalsIgnoreCase(stepName)){
            topTipsView.setVisibility(View.VISIBLE);
            topTipsTv.setText(getText(R.string.top_tips_contact));
        }else topTipsView.setVisibility(View.GONE);

        if (CountryInfo_boom.gInstance().isEnglish())
            titleView.setTitle(Stringutil_boom.processTitleFormat(stepName));
        else titleView.setTitle(ProcessInfo_boom.getInstance().gStepTitle());

        //联系人信息单独处理
        if (step.isContact()){

            for (int i = 0; i< step.gExtDataListSize(); i++){
                ProcessData_boom data = step.gExtProcessData(i);
                if (data==null) continue;
                addInputView(data,null);
            }

            //添加分割线
            if (step.gExtDataListSize()>0) groupLayout.addView(LayoutInflater.from(this).inflate(R.layout.view_line_boom,null));

            int count = 0;

            while (count < step.gItemCount()){//联系人数量

                View contactTitleView = View.inflate(this,R.layout.view_contact_title,null);
                TextView titleTv = contactTitleView.findViewById(R.id.view_contact_title_tv_title);
                titleTv.setText(count==0 ? getString(R.string.contact_title_1):getString(R.string.contact_title_2,(count+1)));
                groupLayout.addView(contactTitleView);

                for (int i = 0; i< step.gDataListSize(); i++){
                    ProcessData_boom data = step.gProcessData(i);
                    if (data==null) continue;
                    addInputView(data, step.gRelationShips(count));
                }

                count++;
            }

            return;
        }

        for (int i = 0; i< step.gDataListSize(); i++){
            ProcessData_boom data = step.gProcessData(i);
            if (data==null) continue;
            addInputView(data,null);
        }
    }

    //添加信息输入控件
    @SuppressLint("InflateParams")
    private void addInputView(ProcessData_boom data, ArrayList<String> relationships){

        View inputView = null;

        switch (data.gAction()){

            case Constant_boom.Data_Action_Select:
                inputView = LayoutInflater.from(this).inflate(R.layout.view_select_boom,null);
                SelectViewManager_boom selectViewManager = new SelectViewManager_boom(inputView,data,pageTag);
                infoInputViewManagers.add(selectViewManager);
                break;

            case Constant_boom.Data_Action_Date_Pick:
                inputView = LayoutInflater.from(this).inflate(R.layout.view_date_picker_boom,null);
                DatePickViewManager_boom datePickWidgetsManager = new DatePickViewManager_boom(inputView,data,pageTag);
                infoInputViewManagers.add(datePickWidgetsManager);
                break;

            case Constant_boom.Data_Action_Relation://联系人-关系
                if (relationships!=null) data.sRelationships(relationships);
                inputView = LayoutInflater.from(this).inflate(R.layout.view_contact_relationship_select_boom,null);
                ContactRelationshipSelectViewManager_boom contactSelectViewManager = new ContactRelationshipSelectViewManager_boom(inputView,data,pageTag);
                infoInputViewManagers.add(contactSelectViewManager);
                break;

            case Constant_boom.Data_Action_Gender_Pick:
                inputView = LayoutInflater.from(this).inflate(R.layout.view_gender_select_boom,null);
                GenderSelectViewManager_boom genderSelectViewManager = new GenderSelectViewManager_boom(inputView,data,pageTag);
                infoInputViewManagers.add(genderSelectViewManager);
                break;

            case Constant_boom.Data_Action_Input:
            case Constant_boom.Data_Action_Name://联系人-名字
            case Constant_boom.Data_Action_Phone://联系人-电话
            default:
                inputView = LayoutInflater.from(this).inflate(R.layout.view_input_boom,null);
                InputViewManager_boom inputWidgetsManager = new InputViewManager_boom(inputView,data,pageTag);
                infoInputViewManagers.add(inputWidgetsManager);
                break;
        }

        if (inputView!=null) groupLayout.addView(inputView);
    }

    //获取银行列表响应（尼日）
    public void onFetchBankCodeResponse(JSONArray jsonArray){

        if (bankNameData == null || jsonArray == null) return;

        map_bankName_bankCode.clear();
        String[] bankNames = new String[jsonArray.length()];

        for (int i = 0;i<jsonArray.length();i++){
            JSONObject jsonObject = jsonArray.optJSONObject(i);
            String bankName = jsonObject.optString("bankName");
            String bankCode = jsonObject.optString("bankCode");
            bankNames[i] = bankName;
            map_bankName_bankCode.put(bankName,bankCode);
        }

        bankNameData.sBankNames(bankNames);
        @SuppressLint("InflateParams") View inputView = LayoutInflater.from(this).inflate(R.layout.view_select_boom,null);
        SelectViewManager_boom selectViewManager = new SelectViewManager_boom(inputView, bankNameData,pageTag);
        infoInputViewManagers.add(selectViewManager);

        groupLayout.addView(inputView);
    }

    @Override
    protected void onStop() {
        super.onStop();
//        private final ArrayList<BaseInfoInputViewManager_boom> infoInputViewManagers = new ArrayList<>();

        for (BaseInfoInputViewManager_boom infoInputViewManager : infoInputViewManagers){
            if (infoInputViewManager!=null) infoInputViewManager.clearInputFocus();
        }

    }
}